package org.algorithm.落雪.数组.三月.第四周;

import java.util.Arrays;

public class 旋转打印数组 {

    public static void main(String[] args) {

//        1 2 3
//        4 5 6
//        7 8 9
        int[][] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

        System.out.println(Arrays.toString (spiralOrder(matrix)));
    }

    public static int[] spiralOrder(int[][] matrix){
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return new int[0];
        }
        int left = 0;//左边界
        int right = matrix[0].length - 1;//右边界
        int top = 0;//上边界
        int bottom = matrix.length - 1,count = 0;//下边界
        int[] result = new int[(right + 1) * (bottom + 1)];

        while (true) {
            //顶部左侧-->顶部右侧
            for(int i = left;i <= right; i++){
                result[count++] = matrix[top][i];
            }
            //最顶上的一行打印完了 top+1 若 top > bottom 则返回
            top = top + 1;
            if(top > bottom)break;

            //从右侧顶部-->右侧底部
            for(int i = top; i <= bottom; i++){
                result[count++] = matrix[i][right];
            }
            //最右侧一列打印完了 right-1 若 right < left 则返回
            right = right -1;
            if(right < left)break;

            //从底部右侧---->底部左侧
            for(int i = right; i >= left; i--){
                result[count++] = matrix[bottom][i];
            }
            //最下面一行打印完了 bottom-1 若 bottom < top 则返回
            bottom = bottom -1;
            if(bottom < top)break;

            //从左侧底部---->左侧顶部
            for(int i = bottom; i >= top; i--){
                result[count++] = matrix[i][left];
            }
            //最左侧一列打印完了 left+1 若 left > right 则返回
            left = left +1;
            if(left > right)break;
        }
        return result;
    }

}
